package com.zhongli.devplatform.controller;


import com.zhongli.devplatform.constant.Consts;
import com.zhongli.devplatform.dto.sys.LoginDTO;
import com.zhongli.devplatform.component.JwtTokenUtil;
import com.zhongli.devplatform.bean.Res;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api(tags = "用户登录认证", description = "用户登录认证", value = "用户登录认证")
@RestController
@CrossOrigin
public class JwtAuthenticationController {
    @Value("${token.expirationMilliSeconds}")
    private long expirationMilliSeconds;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("用户认证")
    @PostMapping("/authenticate")
    public Res createAuthenticationToken(@RequestBody LoginDTO loginDTO) {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginDTO.getAccountNum(), loginDTO.getPassword()));
        } catch (DisabledException e) {
            return Res.error("系统验证失败");
        } catch (BadCredentialsException e) {
            return Res.error("用户名或密码错误");
        }
        final UserDetails userDetails = userDetailsService
                .loadUserByUsername(loginDTO.getAccountNum());
        //封装redis集合
        String key = Consts.USER_TOKEN + userDetails.getUsername();
        //获取token
        String token = jwtTokenUtil.generateToken(userDetails);
        //放入redis
        stringRedisTemplate.opsForValue().set(key,token, expirationMilliSeconds, TimeUnit.MILLISECONDS);

        return new Res<>(0,"登录成功",token);
    }

}
